package org.filecollector.filecontroller.basicsfilecontroller;

import org.filecollector.filecontroller.cataloguemap.CatalogueMap;
import org.filecollector.filecontroller.virtualcatalogue.VirtualCatalogueFactory;
import org.filecollector.filecontroller.virtualcatalogue.groupname.GroupName;

import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public abstract class BasicsFileControllerFactory {
    public static BasicsFileController create(
            BasicsFileControllerDao data,
            BasicsFileControllerDependencies dependencies
    ) {
        return new BasicsFileControllerClass(data, dependencies);
    }

    /**
     * Creates File Controller depending on string list
     * @param name name of File Controller
     * @param dirs directories paths in string format
     * @param dependencies FileController dependencies
     * @return Optional.of(BasicsFileController) or Optional.empty() if name doesn't include any of dirs
     * or if any dirs is intersecting each others.
     */
    public static Optional<BasicsFileController> createByListOfFiles(
            GroupName name,
            List<String> dirs,
            BasicsFileControllerDependencies dependencies
    ) {
        var stream = dirs.stream().filter(Objects::nonNull)
                .map((String a) -> VirtualCatalogueFactory.constructFromString(
                        a,
                        dependencies.virtualCatalogueDependenciesProducer().apply(a)
                        )
                )
                .filter(Optional::isPresent)
                .map(Optional::get);
        if (stream.anyMatch(a -> !name.includes(a.getName()))) {
            return Optional.empty();
        }
        var opt = CatalogueMap.constructFromStream(stream);
        if (opt.isEmpty()) {
            return Optional.empty();
        }
        var dao = new BasicsFileControllerDao(opt.get(), name);
        return Optional.of(new BasicsFileControllerClass(dao, dependencies));
    }
}
